import 'package:flutter/material.dart';
import 'package:shenlingwuliu_flutter/utils/http.dart';
import 'package:shenlingwuliu_flutter/utils/toast.dart';

class WaitingPage extends StatefulWidget {
  const WaitingPage({super.key});

  @override
  State<WaitingPage> createState() => _WaitingPageState();
}

class _WaitingPageState extends State<WaitingPage> {
  List taskList = [];
  int page = 1;
  int pageSize = 10;
  int status = 1;
  ScrollController _scrollController = ScrollController();
  bool _isLoadingMore = false;
  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_loadMoreData);
    getData();
  }

  @override
  void dispose() {
    _scrollController.removeListener(_loadMoreData);
    _scrollController.dispose();
    super.dispose();
  }

  void getData() async {
    var res = await http.get(
      '/driver/tasks/list?page=$page&pagesize=$pageSize&status=$status',
    );

    setState(() {
      taskList = res['data']['items'];
    });
  }

  void addData() async {
    var res = await http.get(
      '/driver/tasks/list?page=$page&pagesize=$pageSize&status=$status',
    );
    ToastUtil.showSuccess('加载成功');
    setState(() {
      taskList.addAll(res['data']['items']);
    });
  }

  void _loadMoreData() async {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      setState(() {
        _isLoadingMore = true;
        page++;
      });
      await Future.delayed(const Duration(seconds: 0));
      addData();
      setState(() {
        _isLoadingMore = false;
      });
    }
  }

  Future<void> _refreshTasks() async {
    setState(() {
      _isLoadingMore = true; // 防止重复触发加载
      page = 1; // 重置页数
      taskList.clear(); // 清空原有数据
    });
    getData();
    setState(() {
      _isLoadingMore = false;
    });
    ToastUtil.showSuccess('刷新成功');
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
        onRefresh: _refreshTasks,
        child: Container(
            margin: const EdgeInsets.all(20),
            child: taskList.isEmpty
                ? const Center(
                    child: CircularProgressIndicator(),
                  )
                : ListView.builder(
                    controller: _scrollController,
                    itemCount: taskList.length + (_isLoadingMore ? 1 : 0),
                    itemBuilder: (context, index) {
                      if (index == taskList.length && _isLoadingMore) {
                        return const Padding(
                          padding: EdgeInsets.symmetric(vertical: 20),
                          child: Center(
                            child: CircularProgressIndicator(),
                          ),
                        );
                      } else {
                        final item = taskList[index];
                        return Container(
                          margin: const EdgeInsets.only(bottom: 20),
                          padding: const EdgeInsets.all(20),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Column(
                            children: [
                              // 任务编号
                              Row(
                                children: [
                                  const Text('任务编号：',
                                      style: TextStyle(
                                          fontSize: 16,
                                          fontWeight: FontWeight.bold)),
                                  Text(item['id'].toString(),
                                      style: const TextStyle(
                                          fontSize: 16,
                                          fontWeight: FontWeight.bold)),
                                ],
                              ),
                              Container(
                                margin: const EdgeInsets.only(top: 10),
                                child: Row(
                                  children: [
                                    Container(
                                      margin: const EdgeInsets.only(right: 10),
                                      width: 25,
                                      height: 23,
                                      decoration: const BoxDecoration(
                                          shape: BoxShape.circle,
                                          color: Colors.black),
                                      child: const Text(
                                        '起',
                                        style: TextStyle(color: Colors.white),
                                        textAlign: TextAlign.center,
                                      ),
                                    ),
                                    Text(item['startAddress'],
                                        style: const TextStyle(
                                          color:
                                              Color.fromRGBO(140, 140, 140, 1),
                                          fontWeight: FontWeight.w400,
                                        ))
                                  ],
                                ),
                              ),
                              Container(
                                margin: const EdgeInsets.only(top: 10),
                                child: Row(
                                  children: [
                                    Container(
                                      margin: const EdgeInsets.only(right: 10),
                                      width: 25,
                                      height: 23,
                                      decoration: const BoxDecoration(
                                          shape: BoxShape.circle,
                                          color: Colors.red),
                                      child: const Text(
                                        '止',
                                        style: TextStyle(color: Colors.white),
                                        textAlign: TextAlign.center,
                                      ),
                                    ),
                                    Text(item['endAddress'],
                                        style: const TextStyle(
                                          color:
                                              Color.fromRGBO(140, 140, 140, 1),
                                          fontWeight: FontWeight.w400,
                                        ))
                                  ],
                                ),
                              ),
                              Container(
                                margin: const EdgeInsets.only(top: 20),
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        const Text('提货时间'),
                                        Text(item['planDepartureTime'])
                                      ],
                                    ),
                                    ElevatedButton(
                                        onPressed: () {},
                                        style: const ButtonStyle(
                                            backgroundColor:
                                                WidgetStatePropertyAll(
                                                    Colors.red)),
                                        child: const Text(
                                          '提货',
                                          style: TextStyle(color: Colors.white),
                                        ))
                                  ],
                                ),
                              )
                            ],
                          ),
                        );
                      }
                    })));
  }
}
